package com.lw.leetcode.arr.a;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * 1389. 按既定顺序创建目标数组
 *
 * @author liw
 * @version 1.0
 * @date 2021/9/17 9:10
 */
public class CreateTargetArray {


    public static void main(String[] args) {
        CreateTargetArray test = new CreateTargetArray();
        // [0,4,1,3,2]
//        int[] nums = {0, 1, 2, 3, 4};
//        int[] indexs = {0, 1, 2, 2, 1};

        // [2,2,4,4,3]
//        int[] nums = {4, 2, 4, 3, 2};
//        int[] indexs = {0, 0, 1, 3, 1};

        // [7,5,4,5,5,6,5,5]
        int[] nums = {7,6,5,5,5,4,5,5};
        int[] indexs = {0,1,1,2,4,2,3,6};

        int[] targetArray = test.createTargetArray(nums, indexs);
        System.out.println(Arrays.toString(targetArray));
    }

    public int[] createTargetArray(int[] nums, int[] index) {
        int length = index.length - 1;
        for (int i = length; i >= 0; i--) {
            int v = index[i];
            int item = v;
            int s = 0;
            for (int j = i + 1; j <= length; j++) {
                if (v + s >= index[j]) {
                    item++;
                    s++;
                }
            }
            nums[item] = ((nums[i] & 127) << 7) | nums[item];
        }
        for (int i = 0; i <= length; i++) {
            nums[i] = nums[i] >> 7;
        }
        return nums;
    }

    public int[] createTargetArray2(int[] nums, int[] index) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums.length; ++i) {
            list.add(index[i], nums[i]);
        }
        int[] ret = new int[nums.length];
        for (int i = 0; i < nums.length; ++i) {
            ret[i] = list.get(i);
        }
        return ret;
    }

}
